package edu.univercidade.tcc.sap.ejb;

import static edu.univercidade.tcc.sap.model.UserStatus.ACTIVE;
import static edu.univercidade.tcc.sap.model.BooleanType.TRUE;
import static edu.univercidade.tcc.sap.model.EmailNotification.NONE;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import edu.univercidade.tcc.sap.model.BooleanType;
import edu.univercidade.tcc.sap.model.EmailNotification;
import edu.univercidade.tcc.sap.model.User;
import edu.univercidade.tcc.sap.model.UserStatus;
import edu.univercidade.tcc.sap.shared.CryptUtil;

/**
 * Session Bean implementation class UserService
 */
@Stateless
public class UserService implements UserServiceLocal {

	@PersistenceContext
	EntityManager em;

	private static final Logger LOGGER = Logger.getLogger(UserService.class);

	public User getUserByLogin(String login) {
		Query q = em.createNamedQuery("userByLogin");
		q.setParameter("login", login);
		User user = null;
		try {
			user = (User) q.getSingleResult();
		} catch (NoResultException e) {
			LOGGER.debug("Usuário " + user + " inexistente", e);
		}
		return user;
	}

	public boolean isValidUser(String user, String password) {
		try {
			Query q = em.createNamedQuery("userByLogin");
			q.setParameter("login", user);
			User validUser = (User) q.getSingleResult();
			if (CryptUtil.hexaSHA1(password).equals(
					validUser.getHashedPassword())) {
				validUser.setLastLoginOn(new Date());
				em.merge(validUser);
				return true;
			}
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	public User createUser(String login, String password, String firstname,
			String lastname, String mail) {
		User user = new User();
		user.setAdmin(TRUE);
		user.setCreatedOn(new Date());
		user.setFirstname(firstname);
		user.setHashedPassword(CryptUtil.hexaSHA1(password));
		user.setLastname(lastname);
		user.setLogin(login);
		user.setMail(mail);
		//TODO mail notification
		user.setMailNotification(NONE);
		user.setStatus(ACTIVE);
		em.persist(user);
		return user;
	}
	
	//TODO call persist only in this one
	public User create(User user) {		
		user.setCreatedOn(new Date());
		//TODO login and password configuration
		user.setLogin(user.getFirstname());
		user.setHashedPassword(CryptUtil.hexaSHA1("123456"));
		//TODO mail notification
		user.setMailNotification(NONE);
		user.setStatus(ACTIVE);
		em.persist(user);
		return user;
	}
	
	public void delete(User user) {
		em.remove(em.getReference(User.class, user.getId()));
	}

	@SuppressWarnings("unchecked")
	@Override
	public User[] listValid() {
		Query q = em.createNamedQuery("usersByStatus");
		q.setParameter("status", ACTIVE);
		return ((List<User>)q.getResultList()).toArray(new User[]{});
	}

	@Override
	public void update(User user) {
		em.merge(user);
	}
}
